import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Main from '@/views/Main.vue'
import UserList from '@/views/User/UserList.vue'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import RoleList from '@/views/Role/RoleList.vue';
import { ElMessage } from 'element-plus'
import RoleAdd from "@/views/Role/RoleAdd.vue";
import UserAdd from '@/views/User/UserAdd.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'main',
    component: Main,
    children: [
      {
        path: '/user/list',
        name: 'userlist',
        component: UserList
      },
      {
        path: '/user/add',
        name: 'useradd',
        component: UserAdd
      },
      {
        path: '/role/list',
        name: 'rolelist',
        component: RoleList
      },
      {
        path: '/role/add',
        name: 'roleadd',
        component: RoleAdd
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
  },
  {
    path: '/register',
    name: 'register',
    component: Register,
  }

]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {

  const token = window.localStorage.getItem("userToken")

  if (to.path == "/login" || to.path == "/register") {
    return next();
  } else {
    if (!token) {
      ElMessage({
        message: "请先登录!",
      })
      return next('/login')
    } else {
      return next();
    }
  }

})

export default router
